package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.userinterface.ResourceTool;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.agconnect.remoteconfig.ConfigValues;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.AbilitySliceAnimator;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.os.ProcessManager;

public class SplashSceneSlice extends AbilitySlice
{

    private EventRunner runner;
    private MyEventHandler myHandler;
    private AbilitySlice abilitySlice;
    private Component AllContent;
    private AnimatorValue animator;

    private class MyEventHandler extends EventHandler
    {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }
        // 重写实现processEvent方法
        @Override
        public void processEvent(InnerEvent event)
        {
            if(event==null)return;
            int code = event.eventId;
            if(code == 0)
            {
                abilitySlice = new MainSceneSlice();
                myHandler.sendEvent(1, 700, EventHandler.Priority.IMMEDIATE);
            }else if(code == 1)
            {
                try{if(animator!=null)animator.release();}catch(Exception ex){}
                try{AllContent.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);}catch(Exception ex){}
                try{AllContent.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);}catch(Exception ex){}
                try{AllContent.setAlpha(1f);}catch(Exception ex){}
                animator.start();
                myHandler.sendEvent(2, 300, EventHandler.Priority.IMMEDIATE);
            }else
            {
                try
                {
                    ThemesEditorAbility.Instance.config = AGConnectConfig.getInstance();
                    ThemesEditorAbility.Instance.config.applyDefault(ResourceTable.Profile_configdefault);
                    int i = 0;
                    String ConfigType = "Local";
                    while((i<3)||((ConfigType.equals("Local"))&&(i<8)))
                    {
                        ConfigValues last = ThemesEditorAbility.Instance.config.loadLastFetched();
                        ThemesEditorAbility.Instance.config.apply(last);
                        ThemesEditorAbility.Instance.config.fetch(3600)
                                .addOnSuccessListener(new OnSuccessListener<ConfigValues>() {@Override public void onSuccess(ConfigValues configValues) {}})
                                .addOnFailureListener(new OnFailureListener() {@Override public void onFailure(Exception e) {}});
                        ConfigType = ThemesEditorAbility.Instance.config.getValueAsString("ConfigType");
                        i++;
                    }
                }
                catch (Exception ex) { }
                super.processEvent(event);
                present(abilitySlice!=null?abilitySlice:new MainSceneSlice(),new Intent());
                terminate();
            }
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_splashscene);
        //设定状态栏沉浸
        getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_splash,0xFEEFF4));
        getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_splash, 0xFDF1F3));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        try
        {
            AbilitySliceAnimator abilitySliceAnimator = new AbilitySliceAnimator(0,0,0,0);
            abilitySliceAnimator.setDuration(0);
            getAbility().setAbilitySliceAnimator(abilitySliceAnimator);
        }catch (Exception ex){ex.printStackTrace();}
        runner = EventRunner.current();
        AllContent = findComponentById(ResourceTable.Id_Slice_root);
        animator = animatorValue();
        myHandler = new MyEventHandler(runner);
        myHandler.sendEvent(0, 200, EventHandler.Priority.IMMEDIATE);
    }

    public AnimatorValue animatorValue()
    {
        //创建数值动画对象
        AnimatorValue mAnimatorValue = new AnimatorValue();
        //动画时长
        mAnimatorValue.setDuration(300);
        //播放前的延迟时间
        mAnimatorValue.setDelay(0);
        //循环次数
        mAnimatorValue.setLoopedCount(0);
        //动画的播放类型
        mAnimatorValue.setCurveType(Animator.CurveType.LINEAR);
        //设置动画过程
        mAnimatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener()
        {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float value)
            {
                if(value>=1f)
                    mAnimatorValue.release();
                else
                {
                    float scaleRatio = 1f+value*0.32f;
                    try{AllContent.setScale(scaleRatio,scaleRatio);}catch(Exception ex){}
                    try{AllContent.setAlpha(1f-value);}catch(Exception ex){}
                }
            }
        });
        return mAnimatorValue;
    }
    @Override
    public void onBackPressed()
    {
        DatabaseManager.Init(this);
        DatabaseManager.setString("QuitBySelf","Yes");
        try{myHandler.removeAllEvent();}catch (Exception e){}
        try{AllContent.release();}catch (Exception e){}
        try{animator.release();}catch (Exception e){}
        runner = null;
        myHandler = null;
        abilitySlice = null;
        AllContent = null;
        animator = null;
        System.gc();
        if(PreloadServiceAbility.isFinished) ProcessManager.kill(ProcessManager.getPid());
        else terminateAbility();
    }

    @Override
    public void onActive() { super.onActive(); }

    @Override
    public void onForeground(Intent intent) { super.onForeground(intent); }
}